<?php

namespace Summer\Shop\Http\Controllers;

use Illuminate\Routing\Controller;
use RLuders\JWTAuth\Classes\JWTAuth;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Input;
use Exception;
use Db;
use Summer\Shop\Models\BrowseModel;
use Summer\Shop\Models\CategoryModel;
use Summer\Shop\Models\FavoriteModel;
use Summer\Shop\Models\ProductModel;
use Summer\Shop\Models\ScoreGoodsModel;
use Summer\Shop\Models\ServiceModel;

class ScoreGoodsController extends Controller
{
    use ApiReturn;
    /**
     * 积分商品列表
     */
    public function index()
    {
        $page=Input::get('page',1);
        $page_size=Input::get('page_size',20);
        $query=ScoreGoodsModel::select();
        $query->with(['product']);
        $records=$query->paginate($page_size,$page);
        $records->each(function ($record){
            if($record->price>0){
                $record->price=$record->score."积分+￥".$record->price;
            }else{
                $record->price=$record->score."积分";
            }

        });
        return $this->apiSuccess('操作成功',$records);
    }

    public function preview(){

        $score_goods_id=Input::get('id');
        $score_goods=ScoreGoodsModel::where('id',$score_goods_id)->where('status',1)->first();
        if(!$score_goods){
            return $this->apiError('没有该兑换商品');
        }
        $product_id=$score_goods->product_id;
        $query=ProductModel::select();
        $query->with([
            'image_preview',
            'images'
        ]);
        $query->where('id',$product_id);
        $record=$query->first();

        //处理积分数据
        if($score_goods->price>0){
            $record->price=$score_goods->score."积分+￥".$score_goods->price;
        }else{
            $record->price=$score_goods->score."积分";
        }
        $record->sales=$score_goods->sales;

        //兼容uview-ui的u-swiper
        $record->images->each(function ($image){
            $image->image=$image->path;
        });
        $service_ids=$record->service_ids;
        if(!empty($service_ids)){
            $services=ServiceModel::with(['cover'])->whereIn('id',$service_ids)->get();
            $services->each(function ($service){
                $service->image=$service->cover->path;
            });
            $record->service=$services;
        }else{
            $record->service=[];
        }
        $return['record']=$record;
        return $this->apiSuccess('操作成功',$return);
    }

}
